<template>
	<view>
		<uni-search-bar v-model="searchKeyword" @input="handleSearch" @clear="handleSearch" placeholder="请输入物品名称"
			radius="5">
		</uni-search-bar>
		<cy-cate ref="cyCate" :categories="categories" :active-category-id="selectedCategoryId"
			:goods-list="currentGoodsList" :showcart="true" :showplus="true" @goodsclick="handleGoodClick"
			@submit="btn_click" @category-click="handleCategoryClick" @scrolltolower="handleScrollToLower" />
	</view>
</template>

<script>
	export default {
		data() {
			return {
				searchKeyword: '',
				categories: [],
				selectedCategoryId: '',
				currentGoodsList: [], // 当前分类的商品列表
				loading: false, // 加载状态
				// 新增分页相关数据
				currentPage: 1,
				total: 0,
				isLastPage: false
			}
		},
		onLoad() {
			this.loadCategories()
		},
		onPullDownRefresh() {
			// console.log('onPullDownRefresh')
			this.handleReset()
			this.loadGoodsList().finally(() => {
				uni.stopPullDownRefresh()
			})
		},
		// 在item.vue中新增
		// onReachBottom() {
		//   if (!this.isLastPage) {
		//     this.loadGoodsList()
		//   }
		// },
		// 在组件销毁时清理定时器
		beforeDestroy() {
			clearTimeout(this.searchTimer)
		},
		methods: {
			async loadCategories() {
				try {
					const obj = uniCloud.importObject('goods')
					const res = await obj.getCategoriesList({})

					if (res.code === 0) {
						this.categories = res.data.map(item => ({
							_id: item._id,
							name: item.name
						}))

						if (this.categories.length > 0) {
							this.selectedCategoryId = this.categories[0]._id
							this.loadGoodsList()
						}
					}
				} catch (error) {
					uni.showToast({
						title: '获取分类失败',
						icon: 'none'
					})
				}
			},

			async loadGoodsList() {
				// 防止重复请求
				if (this.loading || this.isLastPage) return

				this.loading = true

				try {
					const requestId = Date.now()
					this.lastRequestId = requestId
					const obj = uniCloud.importObject('goods')
					const res = await obj.getGoods({
						queryCondition: {
							category_id: this.selectedCategoryId,
							name: this.searchKeyword ? {
								$regex: this.searchKeyword,
								$options: 'i'
							} : undefined
						},
						pageNum: this.currentPage,
						pageSize: 10
					})

					// 只处理最新请求
					if (requestId !== this.lastRequestId) return

					if (res.code === 0) {
						// 统一重置购物车数量
						const newData = res.data.map(g => ({
							...g,
							_cartNumber: 0 // 强制重置为0
						}))
						if (this.currentPage === 1) {
							this.currentGoodsList = newData
						} else {
							this.currentGoodsList = [
								...this.currentGoodsList,
								...newData.filter(newItem =>
									!this.currentGoodsList.some(item =>
										item._id === newItem._id
									)
								)
							]
						}

						// 更新分页状态
						this.total = res.total
						this.isLastPage = this.currentPage * 10 >= res.total
						this.currentPage++
					}
				} catch (error) {
					console.error('加载失败:', error)
				} finally {
					this.loading = false
				}
			},
			handleSearch() {
				this.handleReset()
			},
			handleReset() {
				clearTimeout(this.searchTimer)
				this.searchTimer = setTimeout(() => {
					// 重置所有相关参数
					this.currentPage = 1
					this.total = 0
					this.isLastPage = false
					this.currentGoodsList = [] // 清空当前列表

					// 强制重置子组件状态
					this.$nextTick(() => {
						this.loadGoodsList()
					})
				}, 1000)
			},
			handleCategoryClick(category) {
				// 修复：避免重复点击相同分类时发送请求
				// console.log(this.selectedCategoryId, category._id, 'handleCategoryClick')
				if (this.selectedCategoryId === category._id) {
					return
				}
				this.currentPage = 1
				this.currentGoodsList = []
				this.isLastPage = false
				this.selectedCategoryId = category._id
				this.loadGoodsList()
			},

			handleGoodClick(goods) {
				uni.$router.to({
					url: '/pagesB/item/detail',
					params: {
						goods: goods
					}
				})
			},

			async update_remaincount(item) {
				try {
					item.remain_count = Number(item.remain_count)
					const obj = uniCloud.importObject('goods')
					const res = await obj.batchUpdateGoods(item)

					if (res.code === 0) {
						uni.showToast({
							title: '更新成功',
							icon: 'success',
							duration: 1000
						})
						// 更新后重新加载商品列表
						// console.log('update_remaincount')
						this.handleReset()
						this.loadGoodsList()
					} else {
						uni.showToast({
							title: `更新失败：${res.message}`,
							icon: 'none',
							duration: 3000
						})
					}
				} catch (e) {
					uni.showToast({
						title: '网络异常，请稍后重试',
						icon: 'none'
					})
				}
			},

			getorderid(userinfo) {
				const now = uni.$dayjs(new Date()).format('YYYYMMDD')
				const randomNum = Math.floor(Math.random() * 900000) + 100000
				const userSuffix = userinfo._id.slice(-4)
				return `${now}-${randomNum}-${userSuffix}`
			},

			async btn_click(item) {
				try {
					const userinfo = uni.getStorageSync('userInfo');
					if (!this.checkSelectedItem(item)) return;

					// 新增库存检查
					const obj = uniCloud.importObject('goods');
					const stockCheck = await obj.checkStockBeforeUpdate(item);

					if (stockCheck.code !== 0) {
						uni.showToast({
							title: stockCheck.message,
							icon: 'none',
							duration: 3000,
							data: stockCheck.insufficientItems // 可展示具体不足商品
						});
						return;
					}

					// 构建领用记录
					const goodsRecord = this.buildGoodsRecord(item, userinfo);
					const res = await obj.addGoodsRecord(goodsRecord);
					this.showResult(res);

					if (res.code === 0) {
						await this.update_remaincount(item);
						setTimeout(() => {
							uni.$router.reLaunch({
								url: '/pages/user/service/menu',
								params: {
									activeIndex: 2
								}
							})
						}, 500)
					}
				} catch (error) {
					this.handleError(error);
				}
			},

			checkSelectedItem(item) {
				if (!Array.isArray(item) || item.length === 0) {
					uni.showToast({
						title: '请先选择物品',
						icon: 'error'
					});
					return false;
				}
				return true;
			},

			buildGoodsRecord(items, userinfo) {
				return items.map(g => ({
					order_id: this.getorderid(userinfo),
					create_date: uni.$dayjs().format('YYYY-MM-DD HH:mm:ss'),
					user_id: userinfo._id,
					user_name: userinfo.username,
					goods: g,
					status: 0
				}));
			},

			showResult(res) {
				uni.showToast({
					icon: res.code === 0 ? 'success' : 'none',
					title: res.message
				});
			},

			handleError(error) {
				uni.showToast({
					icon: 'error',
					title: '请求失败，请检查网络'
				});
			},
			handleScrollToLower() {
				if (!this.isLastPage) {
					this.loadGoodsList()
				}
			},
		}
	}
</script>

<style>
	/* 添加样式 */
</style>